package com.jnu.hc.jnuhcusercms.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jnu.hc.jnuhcusercms.domain.Users;
import com.jnu.hc.jnuhcusercms.dto.ResponseObject;
import com.jnu.hc.jnuhcusercms.service.UsersService;
import com.jnu.hc.jnuhcusercms.service.UsersServiceImpl;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

//处理用户请求的控制器
@RestController
public class UserController {
    @Autowired
    UsersServiceImpl usersService;
    //处理登录请求
    @RequestMapping("/login")
    public ResponseObject<Users> login(@RequestBody Users users, HttpServletResponse response) throws JsonProcessingException {
        System.out.println("users:"+users.getUserId()+","+users.getPassword());
       // Users u=null;
       // ResponseObject<Users> responseObject=new ResponseObject<>(200,"success",u);
        ResponseObject<Users> responseObject=usersService.login(users);
        if(responseObject.getStatus()==200){
            Map<String,Object> map=new HashMap<>();
            map.put("currentUser",new ObjectMapper().writeValueAsString(users));
            JwtBuilder builder = Jwts.builder()
                    .id(UUID.randomUUID().toString())
                    .issuedAt(new Date())
                    .signWith(getSigningKey())
                    .expiration(new Date(System.currentTimeMillis() + 1000*60*24))
                    .claims(map).subject(users.getUserId());
            String key=builder.compact();
            responseObject.setToken(key);
        }
        return responseObject;
    }
    private SecretKey getSigningKey() {
        byte[] keyBytes = Decoders.BASE64.decode("my1very1long1secret1at1least1321bytes1long1");
        return Keys.hmacShaKeyFor(keyBytes);}
}
